// src/pages/RoleList/components/PermissionAssignDrawer.tsx
import React, {useState, useEffect} from 'react';
import type {PermissionNode} from '@/types/permission';
import {
    Drawer,
    Tree,
    Button,
    message,
    Spin,
    Space,
} from 'antd';
import type {DataNode} from 'antd/es/tree';
import {getPermissionTree, bindRolePermission} from '@/services/permission'; // 请确认 bindRolePermission 接口路径
import {callApi} from '@/utils/request';

// 将后端 SysPermissionTree 转为 AntD TreeNode
const transformToTreeData = (nodes: any[]): DataNode[] => {
    return nodes.map((item) => ({
        title: (
            <span>
        {item.name} {item.type === 2 && <span style={{color: '#1890ff', fontSize: '12px'}}>（按钮）</span>}
      </span>
        ),
        key: String(item.id),
        children: item.children && item.children.length > 0 ? transformToTreeData(item.children) : [],
        checkable: true,
        checked: item.bindFlag === true,
        disabled: false,
    }));
};

type PermissionAssignDrawerProps = {
    open: boolean;
    roleId: number;
    onClose: () => void;
    onSuccess: () => void;
};

const PermissionAssignDrawer: React.FC<PermissionAssignDrawerProps> = ({
                                                                           open,
                                                                           roleId,
                                                                           onClose,
                                                                           onSuccess,
                                                                       }) => {
    const [treeData, setTreeData] = useState<DataNode[]>([]);
    const [checkedKeys, setCheckedKeys] = useState<React.Key[]>([]);
    const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
    const [loading, setLoading] = useState(true);

    // 加载权限树
    useEffect(() => {
        if (open && roleId) {
            loadPermissionTree();
        }
    }, [open, roleId]);

    const loadPermissionTree = async () => {
        setLoading(true);
        try {
            const response = await callApi<PermissionNode[]>(
                () => getPermissionTree({roleId}),
                {errorMsg: '加载权限树失败'}
            );
            console.log(response)
            if (response) {
                const data = transformToTreeData(response);
                setTreeData(data);
                // 提取所有 bindFlag=true 的节点 id 作为初始勾选项
                const extractCheckedKeys = (nodes: any[]): React.Key[] => {
                    let keys: React.Key[] = [];
                    for (const node of nodes) {
                        if (node.bindFlag) keys.push(String(node.id));
                        if (node.children) keys = keys.concat(extractCheckedKeys(node.children));
                    }
                    return keys;
                };
                setCheckedKeys(extractCheckedKeys(response));

                // 默认展开所有节点
                const getAllKeys = (nodes: any[]): React.Key[] => {
                    let keys: React.Key[] = [];
                    for (const node of nodes) {
                        keys.push(String(node.id));
                        if (node.children) keys = keys.concat(getAllKeys(node.children));
                    }
                    return keys;
                };
                setExpandedKeys(getAllKeys(response));
            }
        } catch (error) {
            console.error('加载权限失败:', error);
        } finally {
            setLoading(false);
        }
    };

    const onCheck = (
        checked: React.Key[] | { checked: React.Key[]; halfChecked: React.Key[] },
        _info: any
    ) => {
        const checkedKeys = Array.isArray(checked) ? checked : checked.checked;
        setCheckedKeys(checkedKeys);
        console.log(checkedKeys)
    };

    const handleSave = async () => {
        const permissionIds = checkedKeys.map(key => Number(key));
        console.log(permissionIds);
        const result = await callApi(
            () => bindRolePermission({roleId, permissionIds}),
            {successMsg: '权限保存成功', errorMsg: '保存失败'}
        );
        if (result) {
            onSuccess();
        }
    };

    const handleExpandAll = () => {
        const getAllKeys = (nodes: DataNode[]): React.Key[] => {
            let keys: React.Key[] = [];
            for (const node of nodes) {
                keys.push(node.key);
                if (node.children) keys = keys.concat(getAllKeys(node.children));
            }
            return keys;
        };
        setExpandedKeys(getAllKeys(treeData));
    };

    const handleCollapseAll = () => {
        setExpandedKeys([]);
    };

    return (
        <Drawer
            title="分配权限"
            width={400}
            open={open}
            onClose={onClose}
            closable={false} // 我们自己控制关闭按钮
            footer={
                <Space style={{float: 'right'}}>
                    <Button onClick={onClose}>关闭</Button>
                    <Button type="primary" onClick={handleSave}>
                        保存
                    </Button>
                </Space>
            }
        >
            <Space style={{marginBottom: 16}}>
                <Button size="small" onClick={handleExpandAll}>
                    全部展开
                </Button>
                <Button size="small" onClick={handleCollapseAll}>
                    全部收起
                </Button>
            </Space>
            <Spin spinning={loading}>
                {treeData.length > 0 ? (
                    <Tree
                        checkable
                        checkedKeys={checkedKeys}
                        onCheck={onCheck}
                        treeData={treeData}
                        expandedKeys={expandedKeys}
                        onExpand={setExpandedKeys}
                        blockNode
                    />
                ) : (
                    !loading && <div style={{textAlign: 'center', color: '#999'}}>暂无权限数据</div>
                )}
            </Spin>
        </Drawer>
    );
};

export default PermissionAssignDrawer;